package com.xxx.bluetooth;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * @author hdz
 */
public class BleClientService extends Service {
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            String btName = device.getName();
            String btAddr = device.getAddress();
            Log.d("==", btName + "==" + btAddr + " " + deviceType2Str(device.getType()) + " " + bondState2Str(device.getBondState()));
        }
    };

    public BleClientService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        startScan();
    }

    @Override
    public void onDestroy() {
        stopScan();
        super.onDestroy();
    }

    private void startScan() {
        //开始扫描蓝牙ble设备
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }

    private void stopScan() {
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }


    /**
     * Get the Bluetooth device type of the remote device.
     */
    public String deviceType2Str(int type) {
        switch (type) {
            case BluetoothDevice.DEVICE_TYPE_CLASSIC:
                return "DEVICE_TYPE_CLASSIC";
            case BluetoothDevice.DEVICE_TYPE_LE:
                return "DEVICE_TYPE_LE";
            case BluetoothDevice.DEVICE_TYPE_DUAL:
                return "DEVICE_TYPE_DUAL";
            case BluetoothDevice.DEVICE_TYPE_UNKNOWN:
                return "DEVICE_TYPE_UNKNOWN";
            default:
                return "DEVICE_TYPE_UNKNOWN(" + type + ")";
        }
    }

    public String bondState2Str(int state) {
        switch (state) {
            case BluetoothDevice.BOND_NONE:
                return "BOND_NONE";
            case BluetoothDevice.BOND_BONDING:
                return "BOND_BONDING";
            case BluetoothDevice.BOND_BONDED:
                return "BOND_BONDED";
            default:
                return "BOND_UNKNOWN(" + state + ")";
        }
    }
}
